<?php
/**
 * Created by PhpStorm.
 * User: fusha_000
 * Date: 10-15/0015
 * Time: 10:32
 */
use pft\Member\MemberAccount;

class ProductSync{
    protected $db;
    public function __construct($db)
    {
        $this->db = $db;
    }
    /**
     * 向终端写入数据
     *
     * @param string $title 产品名称
     * @param string $salerid 资源方6位数账号
     * @param int $mode 操作模式0写入1更新
     * @param string $src_title 所属产品名称
     * @param string $dlTxt 延迟验证
     * @return mixed
     */
    protected function _Write2Remote($title,$salerid,$mode=0,$src_title='', $dlTxt=NULL) {
        $soap = \Sync::GetMulSoap();
        $s    = $soap['cur_soap'];
        $title .= !empty($src_title) ? $src_title:'';
        if($mode==1) {
            return $s->Terminal_CFG_Update($title,$salerid,$dlTxt);
        }
        //echo  $salerid;exit;
        $res = $s->Terminal_CFG($title,$salerid,$dlTxt);
//        var_dump($res);
        if(strpos($res,'|')!==false) {
            $t_no = explode('|', $res);
            return  array(
                'status' => 'ok',
                'msg'  => '生成终端号成功',
                'body' => $t_no[1]
            );
        }
        return array(
            'status' => 'fail',
            'msg'  => $res,
            'body' => ''
        );
    }
    /**
     * 添加产品
     *
     * @param array $params 字段名=>值（参考uu_land表）
     * @param MemberAccount $mem MemberAccount的实例
     * @param INT $parent_id 关系表(pft_member_relationship)中的parent_id
     * @return mixed
     */
    public function AddProduct($params, MemberAccount $mem, $parent_id=0, $dltxt=NULL)
    {
        $memParams = array(
            'dname'=>$params['title'],
            'dtype'=>2,//直接供应方
            'password'=>'b81b84c7961ac41a9e619458511a98d9',//md5(md5('uu654321'))
        );
        //生成直接供应商
        $reg_res = $mem->register($memParams, array());
        if($reg_res['status']=='ok') {
            $res_account = explode('|', $reg_res['body']);
            $params['salerid'] = $res_account[1];
            if(strlen($params['salerid'])>6) {
                return array('errcode'=>1001,'msg'=>'添加失败，商户ID超出长度！');
            }
            //建立直接供应商与供应商关系
            $rel_res = $mem->createRelationship($params['apply_did'],
                $reg_res['body'],1,1);
            //TODO:建立直接供应方与直接供应方平级关系
            if($parent_id>0) {
                $res_res_p = $mem->createRelationship($parent_id,
                    $reg_res['body'],1,2);
            }
            if($reg_res['status']!='ok'){
                return $rel_res;
            }
        }
        else {
            return $reg_res;
        }
        //检测是否存在相同的产品名称，若存在则将产品名称重命名
        $strChkTitle = "SELECT COUNT(*) AS c FROM uu_land WHERE title='{$params['title']}'";
        $this->db->query($strChkTitle);
        $this->db->fetch_assoc();
        $count = $this->db->f('c');
        $src_title = $count>0? '_' . ($count+1):'';

        $res = self::_Write2Remote($params['title'], $params['salerid'],0,$src_title,$dltxt);
        if($res['status']=='ok') {
            $params['terminal'] = $res['body'];
            $params['status'] = 1;
            $stradd = sqlInsert('uu_land', $params);
            if($this->db->query($stradd)) {
                return array('status'=>'ok','msg'=>'添加成功','lastid'=>Sync::LastInsertID());
            }
            else {
                return $this->ErrArr;
            }
        }
        else {
            //$this->RemoveSaler($params['salerid']);
            return array('status'=>'fail','msg'=>"终端数据写入失败，可能是由于存在相同的产品名称导致，请您更改产品名称试试吧！\n（错误代码：{$res['msg']}）");
        }
    }
    /**
     * 根据相应字段验证产品是否已经存在
     *
     * @param string $pro 验证字段的值
     * @param string $colmn 字段名
     * @param array $other 字段名
     * @return mixed
     */
    protected function _chkProExist($pro, $colmn, $other=array())
    {
        $str = "SELECT COUNT(*) AS c FROM uu_land WHERE `{$colmn}`='{$pro}'";
//        echo $str;
        if(!empty($other) && is_array($other)) {
            $str .= " AND " . self::getValues($other);
        }
//        echo $str;
        $this->db->query($str);
        $this->db->fetch_assoc();
        return $this->db->f('c');
    }
    /**
     * 获取产品总表ID
     *
     * @param $id 门票ID
     * @param $debug
     * @return mixed
     */
    protected function _getPid($id, $debug=false)
    {
        $str = "SELECT pid FROM uu_jq_ticket WHERE id={$id} LIMIT 1";
        if ($debug) {
            echo 'getPid=', $str, '<br/>';
        }
        $this->db->query($str);
        $this->db->fetch_assoc();
    }
    /**
     * 同步添加景区门票
     *
     * @param array $data 门票表(uu_jq_ticket)字段名=>值
     * @param bool $debug 是否打开调试
     * @return array
     */
    public function AddTickets($data, $debug=false) {
        //TODO-done:验证景区是否已经存在，不存在的禁止添加
        if(! self::_chkProExist($data['landid'], 'id','uu_land')) {
            //echo '2';
            return array('status'=>'fail','msg'=>'景区不存在，添加失败');
        }
        $str = sqlInsert('uu_jq_ticket', $data);
        if($debug) {
            echo 'AddTickets = ', $str ,"<br/>\n";
        }
        if($this->db->query($str)) {
            $lastid = Sync::LastInsertID();
            $pid = self::_getPid($lastid, $debug);
            return array(
                'status'=>'ok',
                'lastid'=>$lastid,
                'pid'   =>$pid,
                'landid'=>$data['landid']
            );
        }
        return array('status'=>'fail');
    }
    /**
     * 更新产品
     * update：
     * 1.更新时间选择后提交无法修改的bug——2013年4月22日23:16:28
     * 2.只更新改变的字段——2013年4月22日23:16:28
     *
     * @param $params
     * @param $id
     * @return mixed
     */
    public function UpdateTicket($params, $id) {
        //TODO-CGP 验证该产品名称是否已经存在
        $vals = '';
        $str = "SELECT * FROM uu_jq_ticket WHERE id={$id} LIMIT 1";
        //echo $str;
        $this->db->query($str);
        $result = $this->db->fetch_assoc();
        if(!$result) {
            return array('status'=>'fai','msg'=>'修改的数据不存在，请刷新页面后重试');
        }
        $chg_old = array();
        $chg_new = array();
        $chg_count = 0;
        foreach($params as $key=>$val) {
            if($key=='open_time' || $key=='end_time') {
                $result[$key] = substr($result[$key],0,10);
            }
            if($params[$key]!=$result[$key]) {
                if($key=='order_end' && $val==''){
                    $vals .= "`{$key}`=NULL,";
                }else{
                    $vals .= "`{$key}`='{$val}',";
                }

                $chg_count += 1;
                $chg_old[$key] = $result[$key];
                $chg_new[$key] = $params[$key];
            }
            else {
                unset($params[$key]);
            }
        }
        if(!strlen($vals)) {
            //更新了<span class="red">0</span>项
            return array('status'=>'ok','msg'=>'保存成功',
                'lastid'=>$id,'pid'=>$result['pid'],'affect_rows'=>$chg_count);
        }
        $str = "UPDATE uu_jq_ticket SET ";
        $str .= rtrim($vals,',');
        $str .= " WHERE id={$id} LIMIT 1";
        //echo $str;
        //return;
        if($this->db->query($str)) {
            return array('status'=>'ok','msg'=>'更新成功','lastid'=>$id,
                'pid'=>$result['pid']);
        }
        return array('status'=>'fail','msg'=>'SQL执行失败SQL=' . $str);
    }
} 